<?php
/**
 * Created by PhpStorm.
 * User: sky
 * Date: 2019/7/16
 * Time: 23:04
 */

namespace App\Repositories;


use App\Models\Post;
use App\Models\PostMeta;
use App\Models\Tag;

class PostsRepositories
{
    public function model()
    {
        return Post::query();
    }

    public function find($id)
    {
        return $this->model()->with(['manyCategory','manyTag','meta'])->where('id',$id)->first();
    }
    public function slug($slug)
    {
        return $this->model()->with(['manyCategory','manyTag'])->where('post_slug',$slug)->firstOrFail();
    }

    public function save($data)
    {

        $post = $this->model()->create($data);
        if(isset($data['category_id']) && !empty($data['category_id']))
        {
            $categoryId =explode(',',$data['category_id']);
            $post->manyCategory()->sync($categoryId);
        }

        if(isset($data['post_tag']) && !empty($data['post_tag']))
        {
            $tagId =$this->tagIds($data['post_tag']);
            $post->manyTag()->sync($tagId);
        }

        if(isset($data['custom']) && is_array($data['custom']) && !empty($data['custom']) )
        {
            $customData=[];
            foreach ($data['custom'] as $key=>$val)
            {
                $customData[]=[
                    'name'=>$key,
                    'value'=>$val,
                    'post_id'=>$post->id,
                ];
            }
            PostMeta::insert($customData);
        }
        return $post;
    }
    public function update($id,$data)
    {
        $updateData=[
            'title'=>$data['title'],
            'post_slug'=>$data['post_slug'],
            'post_thumb'=>$data['post_thumb'],
            'post_jump_url'=>$data['post_jump_url'],
            'post_author'=>isset($data['post_author'])?$data['post_author']:null,
            'post_source'=>isset($data['post_source'])?$data['post_source']:null,
            'post_date'=>isset($data['post_date'])?$data['post_date']:null,
            'post_template'=>isset($data['post_template'])?$data['post_template']:null,
            'comment_status'=>isset($data['comment_status'])?1:0,
            'post_sort'=>isset($data['post_sort'])?$data['post_sort']:null,
            'post_status'=>isset($data['post_status'])?1:0,
            'post_read_num'=>isset($data['post_read_num'])?$data['post_read_num']:null,
            'post_content'=>$data['post_content'],
            'parent_id'=>isset($data['parent_id'])?$data['parent_id']:0,
            'post_password'=>isset($data['post_type'])?$data['post_type']:'post',

        ];
        $post =$this->find($id);
        if($post->update($updateData))
        {
            if(isset($data['category_id']) && !empty($data['category_id']))
            {
                $categoryId =explode(',',$data['category_id']);
                $post->manyCategory()->sync($categoryId);
            }

            if(isset($data['post_tag']) && !empty($data['post_tag']))
            {
                $tagId =$this->tagIds($data['post_tag']);
                $post->manyTag()->sync($tagId);
            }

            if(isset($data['custom']) && is_array($data['custom']) && !empty($data['custom']) )
            {

                foreach ($data['custom'] as $key=>$val)
                {
                    //PostMeta::where('post_id',$id)->where('name',$key)->update(['value'=>$val]);
                    PostMeta::updateOrCreate(['post_id' => $id, 'name' => $key], ['value' => $val]);
                }

            }

            return true;
        }

        return false;
    }

    public function search($data)
    {

        if(isset($data['recycle']) && $data['recycle'] == 1)
        {
            $model = $this->model()->onlyTrashed()->with(['manyCategory','manyTag']);
        }
        else
        {
            $model = $this->model()->with(['manyCategory','manyTag']);
        }

        if(isset($data['title']))
        {
            $model = $model->where('title','like','%'.$data['title'].'%');
        }
            //



        if(isset($data['category_id']) && $data['category_id'] > 0)
        {
            $model = $model->whereHas('manyCategory',function ($query) use($data) {
                $query->where('id',$data['category_id']);
            });
        }

        if(isset($data['post_type']))
        {
            $model = $model->where('post_type',$data['post_type']);

        }

        $data['limit'] = isset($data['limit'])? $data['limit']:20;

        //些处扩展更多查询条件


        return $model->orderBy('id','desc')->paginate($data['limit'])->toArray();
    }

    public function delete($ids)
    {
        return Post::destroy($ids);
    }

    public function tagIds($tags)
    {
        $tags = explode(",", $tags);
        $tagIds = [];
        foreach ($tags as $tagName) {
            $tag = Tag::firstOrCreate(['name' => trim($tagName)]);
            $tagIds[] = $tag->id;
        }
        return $tagIds;
    }
    public function restore($id)
    {
        return $this->model()->onlyTrashed()->whereIn('id',$id)->restore();
    }

    public function allPages($postType='page')
    {
        return tree_category($this->model()->where('post_type',$postType)->get()->toArray());
    }

    public function childsPages()
    {
        return $this->model()->with(['allChilds'])->where('post_type','page')->paginate(3)->toArray();
        return Post::allChilds();
    }

    public function last($num=6)
    {
        return $this->model()->where('post_type','post')->limit($num)->orderBy('updated_at','desc')->get();
    }

    public function listMeta()
    {
        return PostMeta::distinct('name')->pluck('name');
    }

}